package com.kssoft.ebd.common;

import com.opencsv.CSVReader;
import com.opencsv.exceptions.CsvException;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;

/**
 * 区划代码转换
 * @author liwu
 * @since 2025/9/19
 */
public class NaXiAreaCode {

    // 存储应急广播平台代码到纳溪本地平台代码的映射
    private static Map<String, String> areaCodeMap = new HashMap<>();

    // CSV文件路径
    private static final String AREA_CODE_CSV = "naxi_area_code_mapping.csv";

    static {
        loadAreaCodeMapping();
    }

    /**
     * 读取CSV文件并加载区划代码映射
     */
    private static void loadAreaCodeMapping() {

        InputStream inputStream;
        if (Files.exists(Paths.get(AREA_CODE_CSV))) {
            try {
                inputStream = new FileInputStream(AREA_CODE_CSV);
            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            }
        }else {
            inputStream = NaXiAreaCode.class.getClassLoader().getResourceAsStream(AREA_CODE_CSV);
        }
        try ( InputStreamReader isr = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
             CSVReader reader = new CSVReader(isr)) {

            List<String[]> records = reader.readAll();
            boolean isFirstLine = true;

            for (String[] record : records) {
                // 跳过标题行
                if (isFirstLine) {
                    isFirstLine = false;
                    continue;
                }

                if (record.length >= 2) {
                    String localCode = record[0].trim();
                    String emergencyCode = record[1].trim();
                    areaCodeMap.put(emergencyCode, localCode);
                }
            }

        } catch (IOException | CsvException e) {
            e.printStackTrace();
        } catch (Exception e) {
            System.err.println("读取区划代码映射文件失败: " + e.getMessage());
        }
    }

    /**
     * 根据应急广播平台代码获取纳溪本地平台代码
     * @param emergencyCode 应急广播平台代码
     * @return 纳溪本地平台代码
     */
    public static String convertToLocalCode(String emergencyCode) {
        return areaCodeMap.getOrDefault(emergencyCode, emergencyCode);
    }

    /**
     * 获取所有区划代码映射
     * @return 区划代码映射表
     */
    public static Map<String, String> getAreaCodeMap() {
        return new HashMap<>(areaCodeMap);
    }
}
